//
//  BCSavePhotoManager.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/28.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCSavePhotoManager.h"



//
@implementation SavePhotoManagerError

@end

@interface BCSavePhotoManagerModel : NSObject

/**
 *image
 */
@property (nonatomic, copy) UIImage *image;

/**
 *SavePhotoManagerCompleted
 */
@property (nonatomic, copy) SavePhotoManagerCompleted saveComplete;

@end

@implementation BCSavePhotoManagerModel


- (void)writeImageComplete:(SavePhotoManagerCompleted)complete {
    self.saveComplete = complete;
    UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (self.saveComplete) {
        if (error) {
            SavePhotoManagerError *saveError = [SavePhotoManagerError new];
            saveError.error = [error copy];
            //
            if ([QMUIAssetsManager authorizationStatus]==QMUIAssetAuthorizationStatusNotAuthorized) {
                saveError.isAuthorization = true;
            }
            self.saveComplete(false, saveError);
        }else {
            self.saveComplete(true, nil);
        }
    }
}


@end


@interface BCSavePhotoManager ()

@property (nonatomic, strong) NSMutableArray *photoManagerModels;

@end

@implementation BCSavePhotoManager

static BCSavePhotoManager *savePhotoManager = nil;
+ (instancetype)sharedSave {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!savePhotoManager) {
            savePhotoManager = [[BCSavePhotoManager alloc] init];
        }
    });
    return savePhotoManager;
}
- (NSMutableArray *)photoManagerModels {
    if (!_photoManagerModels) {
        _photoManagerModels = [NSMutableArray array];
    }
    return _photoManagerModels;
}



- (void)savePhotoToAlbum:(UIImage *)image complete:(SavePhotoManagerCompleted)complete{
    /**
     怕万一没有鉴权
     */
    [QMUIAssetsManager requestAuthorization:nil];
    //
    BCSavePhotoManagerModel *model = [BCSavePhotoManagerModel new];
    model.image = image;
    [self.photoManagerModels addObject:model];
    //
    WEAK_SELF
    [model writeImageComplete:^(BOOL success, SavePhotoManagerError *error) {
        [wself.photoManagerModels removeObject:model];
        if (complete) {
            complete(success,error);
        }
    }];
}


@end
